package com.quan.weixin.tools;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.HttpClient;
import com.mzlion.easyokhttp.response.HttpResponse;
import com.quan.base.common.utils.HttpClientUtil;
import com.quan.weixin.api.API;
import com.quan.weixin.common.WeixinUtil;
import com.quan.weixin.model.QrCode;
import com.quan.weixin.model.QrCodeTicket;
import com.quan.weixin.model.SubscribeUser;
import com.quan.weixin.model.UserDetail;

public class WeiXinTools {
	
	private static Logger logger = LoggerFactory.getLogger(WeiXinTools.class);

	/**
	 * 推送菜单到微信
	 * @param accessToken
	 * @param menuJson
	 * @return
	 */
	public static JSONObject pushMenuToWeiXin(String accessToken, String menuJson) {
		String response = HttpClientUtil.post(API.get(API.MENU_CREATE_URL, accessToken), menuJson, "utf-8");
		return JSON.parseObject(response) ;
	}
	
	/**
	 * 获取用户列表
	 * @param accessToken
	 * @param next_openid
	 * @return
	 */
	public static SubscribeUser getSubscribeUserList(String accessToken, String next_openid) {
		String asString = WeixinUtil.doGet(API.get(API.USER_LIST_URL, accessToken, StringUtils.isNotBlank(next_openid) ? next_openid : "")).asString();
		SubscribeUser subscribeUser = JSON.parseObject(asString, SubscribeUser.class) ;
		
		if(subscribeUser.getData() != null) {
			JSONObject parseObject2 = JSON.parseObject(asString);
			JSONObject parseObject3 = JSON.parseObject(parseObject2.get("data").toString());
			JSONArray parseArray = JSON.parseArray(parseObject3.get("openid").toString()) ;
			List<String> openids = new ArrayList<String>() ;
			for (Object openid : parseArray) {
				openids.add(openid.toString());
			}
			subscribeUser.setData(openids);
		}
		
		return subscribeUser;
	}

	/**
	 * 获取用户基本信息(UnionID机制)
	 * @param accessToken
	 * @param openid
	 * @return
	 */
	public static UserDetail getUserDetail(String accessToken, String openid) {
		UserDetail detail = WeixinUtil.doGet(API.get(API.USER_DETAIL_URL, accessToken, openid)).asBean(UserDetail.class) ;
		return detail;
	}

	/**
	 * 生成临时二维码，默认过期时间（7天）
	 * @param accessToken 公众号的全局唯一接口调用凭据
	 * @param sceneValue 场景值
	 * @return
	 */
	public static String showQRCodeTemp(String accessToken, Object sceneValue) {
		return showQRCodeTemp(accessToken, null, "QR_STR_SCENE", sceneValue) ;
	}
	/**
	 * 生成临时二维码
	 * @param accessToken 公众号的全局唯一接口调用凭据
	 * @param expire_seconds 过期时间（秒）
	 * @param sceneValue 场景值
	 * @return
	 */
	public static String showQRCodeTemp(String accessToken, Long expire_seconds, Object sceneValue) {
		return showQRCodeTemp(accessToken, expire_seconds, "QR_STR_SCENE", sceneValue) ;
	}
	
	/**
	 * 生成临时二维码，默认过期时间（7天）
	 * @param accessToken 公众号的全局唯一接口调用凭据
	 * @param action_name 临时整形参数值：QR_SCENE, 临时字符参数值：QR_STR_SCENE
	 * @param sceneValue 场景值
	 * @return
	 */
	public static String showQRCodeTemp(String accessToken, String action_name, Object sceneValue) {
		return showQRCodeTemp(accessToken, null, action_name, sceneValue) ;
	}
	/**
	 * 生成临时二维码
	 * @param accessToken 公众号的全局唯一接口调用凭据
	 * @param expire_seconds 过期时间（默认7天:604800）：秒
	 * @param action_name 临时整形参数值：QR_SCENE, 临时字符参数值：QR_STR_SCENE
	 * @param sceneValue 场景值
	 * @return 二维码图片的URL
	 */
	public static String showQRCodeTemp(String accessToken, Long expire_seconds, String action_name, Object sceneValue) {
		//获取创建二维码ticket
		String qrCodeTicket = null ;
		
		if("QR_SCENE".equals(action_name)) {//整形参数
			if(null != sceneValue) {//带场景值
				try {
					qrCodeTicket = QrCodeTicket.sceneIntVal(expire_seconds, action_name, Integer.parseInt(sceneValue.toString()));
				} catch (NumberFormatException e) {
					return "场景值参数需为整形" ;
				}
			} else {
				qrCodeTicket = QrCodeTicket.sceneIntVal(expire_seconds, action_name);
			}
			logger.debug("创建二维码ticket：{}", qrCodeTicket);
		} 
		
		if("QR_STR_SCENE".equals(action_name)) {//字符参数
			if(null != sceneValue) {//带场景值
				qrCodeTicket = QrCodeTicket.sceneStrVal(expire_seconds, action_name, sceneValue.toString());
			} else {
				qrCodeTicket = QrCodeTicket.sceneStrVal(expire_seconds, action_name);
			}
		}
		
		if(null != qrCodeTicket) {
			try {
				HttpResponse response = HttpClient.textBody(API.get(API.QR_CODE_TICKET_URL, accessToken)).json(qrCodeTicket).execute();
				QrCode qrCode = response.asBean(QrCode.class) ;
				logger.debug("获取二维码Ticket：{}", qrCode);
				if(null != qrCode) {
					//返回二维码图片的URL
					String qrCodeUrl = API.get(API.QR_CODE_SHOW_URL, URLEncoder.encode(qrCode.getTicket(), "UTF-8")) ;
					logger.debug("临时二维码图片URL：{}", qrCodeUrl);
					return qrCodeUrl ;
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 生成永久二维码
	 * @param accessToken
	 * @param action_name 永久整形参数值：QR_LIMIT_SCENE, 永久字符参数值：QR_LIMIT_STR_SCENE
	 * @param sceneValue 场景值
	 * @return 二维码图片的URL
	 */
	public static String showQRCodeForever(String accessToken, String action_name, Object sceneValue) {
		//获取创建二维码ticket
		String qrCodeTicket = null ;
		
		//整形参数
		if("QR_LIMIT_SCENE".equals(action_name)) {
			if(null != sceneValue) {//带场景值
				try {
					qrCodeTicket = QrCodeTicket.sceneIntVal(action_name, Integer.parseInt(sceneValue.toString()));
				} catch (NumberFormatException e) {
					return "场景值参数需为整形" ;
				}
			} else {
				qrCodeTicket = QrCodeTicket.sceneIntVal(action_name);
			}
			logger.debug("创建二维码ticket：{}", qrCodeTicket);
		}
		if("QR_LIMIT_STR_SCENE".equals(action_name)) {
			if(null != sceneValue) {//带场景值
				qrCodeTicket = QrCodeTicket.sceneStrVal(action_name, sceneValue.toString());
			} else {
				qrCodeTicket = QrCodeTicket.sceneStrVal(action_name);
			}
		}
		if(null != qrCodeTicket) {
			try {
				HttpResponse response = HttpClient.textBody(API.get(API.QR_CODE_TICKET_URL, accessToken)).json(qrCodeTicket).execute();
				QrCode qrCode = response.asBean(QrCode.class) ;
				logger.debug("获取二维码Ticket：{}", qrCode);
				if(null != qrCode) {
					//返回二维码图片的URL
					String qrCodeUrl = API.get(API.QR_CODE_SHOW_URL, URLEncoder.encode(qrCode.getTicket(), "UTF-8")) ;
					logger.debug("永久二维码图片URL：{}", qrCodeUrl);
					return qrCodeUrl ;
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 删除永久素材
	 * @param mediaId
	 * @return
	 */
	public static JSONObject deleteMedia(String accessToken, String mediaId) {
		String delMediaUrl = API.get(API.DELETE_MEDIA_URL, accessToken) ;
		Map<String, String> params = new HashMap<String, String>() ;
		params.put("media_id", mediaId) ;
		
		String asString = WeixinUtil.doPost(delMediaUrl, params).asString();
		return JSON.parseObject(asString);
	}

	/**
	 * 批量删除永久素材
	 * @param accessToken
	 * @param mediaId
	 * @return
	 */
	public static boolean deleteMedia(String accessToken, List<String> mediaIds) {
		for (String mediaId : mediaIds) {
			String delMediaUrl = API.get(API.DELETE_MEDIA_URL, accessToken) ;
			Map<String, String> params = new HashMap<String, String>() ;
			params.put("media_id", mediaId) ;
			
			String asString = WeixinUtil.doPost(delMediaUrl, params).asString();
			JSONObject parseObject = JSON.parseObject(asString);
			Integer errcode = parseObject.getInteger("errcode") ;
			if(errcode == 0) {
				logger.debug("删除永久图文素材成功,MediaId：{}", mediaId );
			} else {
				logger.debug("删除永久图文素材失败,MediaId：{}", parseObject.toString() );
			}
		}
		
		return true;
	}
	
}
